package com.sky.robot.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

public class ProcessUtil {

    private static ProcessBuilder processBuilder = new ProcessBuilder();

    public static Process exec(List<String> commend) {
        Process process = null;
        try {
            String[] commends = new String[commend.size()];
            //将一个可遍历的commends对象流转换成一个新的String数组。实现原理是将commends对象流中的元素依次收集并创建一个新的String数组。
            //这种转换方法的优点是它避免了直接将commends对象转换为String[]数组时可能出现的并发问题。如果commends是一个 parallelCollection，
            // 那么直接转换可能会导致并发问题，因为commends的元素可能会被并发访问。使用toArray方法可以确保线程安全，同时提高性能。
            commend.toArray(commends);
            processBuilder.command(commends);
            process = processBuilder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return process;
    }

    public static String getOutput(Process process) {
        String output = null;
        BufferedReader reader = null;
        try {
            if (process != null) {
                StringBuffer stringBuffer = new StringBuffer();
                // StandardCharsets.UTF_8 是 Java 中的一个常量，表示 UTF-8 字符编码。它是 Java 标准库中的一个类，用于定义常用的字符编码。
                reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                while (reader.read() != -1) {
                    stringBuffer.append(reader.readLine());
                }
                output = stringBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        closeQuietly(reader);
        return output;
    }

    public static String getError(Process process) {
        String errput = null;
        BufferedReader reader = null;
        try {
            if (process != null) {
                StringBuffer stringBuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                while (reader.read() != -1) {
                    stringBuffer.append("\n" + reader.readLine());
                }
                errput = stringBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        closeQuietly(reader);
        return errput;
    }

    public static void closeQuietly(Reader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static void destroy(Process process) {
        if (process != null) {
            process.destroyForcibly();
        }
    }

}